package com.alt.ui;

import java.net.SocketException;
import java.util.Arrays;

import com.alt.R;
import com.alt.base.ALTBaseActivity;
import com.alt.handler.CMCmdHandler;
import com.alt.manager.ALTAppMgr;
import com.alt.manager.ALTPTCMgr;
import com.alt.manager.ALTPTCMgr.ACCOUNT_LOG_TYPE;
import com.alt.manager.ALTPTCMgr.AccountType;
import com.alt.manager.ALTPTCMgr.SCREEN_UI;
import com.alt.manager.ALTPTCMgr.ValidateUserResponse;
import com.alt.models.AccessDeviceInfo;
import com.alt.models.AdsInfo;
import com.alt.models.UserData;
import com.alt.models.UserLogInfo;
import com.alt.shared.IActivityHandler;
import com.alt.utils.ALTSysUtils;
import com.facebook.FacebookException;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.android.Facebook;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ALTLogin extends ALTBaseActivity implements IActivityHandler {

	private EditText edtUsername, edtPassword;
	private Button btnLogin, btnRegister;
	LoginButton authButton;
	private boolean isFacebook = false;

	// FACEBOOK SDK
	// private static final String URL_PREFIX_FRIENDS =
	// "https://graph.facebook.com/me/friends?access_token=";
	// private Session.StatusCallback statusCallback = new
	// SessionStatusCallback();
	private GraphUser userfb;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_login);
		onSetScreenMode(SCREEN_UI.LOGIN);

		iniControls();

		authButton = (LoginButton) findViewById(R.id.btnSignup);
		authButton.setOnErrorListener(new OnErrorListener() {

			@Override
			public void onError(FacebookException error) {
				Log.i("HAI", "Error " + error.getMessage());
			}
		});
		// set permission list, Don't forget to add email
		authButton.setReadPermissions(Arrays.asList("basic_info", "email", "status_update"));
		// session state call back event
		// authButton.setSessionStatusCallback(this);
		authButton.setSessionStatusCallback(new Session.StatusCallback() {

			@Override
			public void call(final Session session, SessionState state, Exception exception) {

				if (session.isOpened()) {
					Log.i("HAI", "Access Token" + session.getAccessToken());
					Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
						@Override
						public void onCompleted(GraphUser user, Response response) {
							if (user != null) {
								ALTAppMgr.isLoginFace = true;
								userfb = user;// set global
								// service process
								ALTAppMgr.getInstance().getUserLogInfoModel().setFacebookID(user.getId());
								Bundle cmdData = new Bundle();
								Log.i("HAI", "Email " + user.asMap().get("email"));
								cmdData.putString("username", user.asMap().get("email").toString());
								cmdData.putString("password", "empty");
								cmdData.putString("deviceid", AccessDeviceInfo.getDeviceID(getApplicationContext()));
								try {
									cmdData.putString("deviceip", AccessDeviceInfo.getDeviceIpAddress());
								} catch (SocketException e) {
									e.printStackTrace();
									cmdData.putString("deviceip", "0000");
								}
								cmdData.putString("accounttype", AccountType.SOCIAL_NETWORK.toString());
								isFacebook = true;
								ALTAppMgr.getInstance().startServiceCmd(CMCmdHandler.COMMAND_VALIDATE_USER, new CMCmdHandler(), cmdData, true);
								// session.closeAndClearTokenInformation();
								// session.close();
							} else {
								Toast.makeText(getApplicationContext(), "Network not good ^^!", Toast.LENGTH_LONG).show();
							}
						}

					});
				}

			}

		});
	}

	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		if (state.isOpened()) {
			Log.i("HAI", "Logged in...");
			ALTAppMgr.isStillLogin = true;
		} else if (state.isClosed()) {
			ALTAppMgr.isStillLogin = false;
			Log.i("HAI", "Logged out...");
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
	}

	private void iniControls() {
		edtUsername = (EditText) findViewById(R.id.edEmail);
		edtPassword = (EditText) findViewById(R.id.edPass);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnRegister = (Button) findViewById(R.id.btnRegister);

		btnRegister.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onEventReceiver(SCREEN_UI.REGISTER);
			}
		});

		btnLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				Session session = Session.getActiveSession();
				if (session != null && (session.isOpened() || session.isClosed())) {
					onSessionStateChange(session, session.getState(), null);
				}

				isFacebook = false;
				ALTAppMgr.isLoginFace = false;
				// validate input data
				if (checkConstraint()) {
					// service process
					Bundle cmdData = new Bundle();
					cmdData.putString("username", String.valueOf(edtUsername.getText()));
					cmdData.putString("password", String.valueOf(edtPassword.getText()));
					cmdData.putString("deviceid", AccessDeviceInfo.getDeviceID(getApplicationContext()));
					try {
						cmdData.putString("deviceip", AccessDeviceInfo.getDeviceIpAddress());
					} catch (SocketException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						cmdData.putString("deviceip", "0000");
					}
					cmdData.putString("accounttype", AccountType.NATIVE.toString());
					// onEventReceiver(SCREEN_UI.MAIN);
					ALTAppMgr.getInstance().startServiceCmd(CMCmdHandler.COMMAND_VALIDATE_USER, new CMCmdHandler(), cmdData, true);
				}
			}
		});

	}

	public Boolean checkConstraint() {

		if (this.edtUsername.getText().toString().trim().equalsIgnoreCase("")) {
			alert("Vui lòng nhập thông tin tài khoản");
			return false;
		}
		if (this.edtPassword.getText().toString().trim().equalsIgnoreCase("")) {
			alert("Vui lòng nhập thông tin tài khoản");
			return false;
		}
		if (!(Boolean) ALTSysUtils.isValidateEmail(this.edtUsername.getText().toString())) {
			alert("Email không chính xác!");
			return false;
		}
		return true;
	}

	@Override
	public void onScreenChanged(SCREEN_UI curScreen) {
		super.onScreenChanged(curScreen);
		finish();
	}

	@Override
	public void processCommandResult(int commandCode, Object resultData) {
		// TODO Auto-generated method stub
		super.processCommandResult(commandCode, resultData);

		Bundle bResult = (Bundle) resultData;

		switch (commandCode) {

		case CMCmdHandler.COMMAND_VALIDATE_USER: {
			UserData uData = (UserData) bResult.getSerializable(ALTPTCMgr.REST_OBJECT_RETURN);

			if (uData.UserId.trim().equals(ValidateUserResponse.NOT_AVAILABLE.toString())) {// not
																							// available
				alert(R.string.msg_login_failed);
				edtUsername.setText("");
				edtPassword.setText("");
				return;
			}

			if (uData.UserId.trim().equals(ValidateUserResponse.LIMITED.toString())) {// not
																						// available
				alert(R.string.msg_login_limited);
				edtUsername.setText("");
				edtPassword.setText("");
				return;
			}

			// Toast.makeText(this, uData.ID, Toast.LENGTH_LONG).show();

			// set temporary user data
			UserLogInfo uLogInfo = new UserLogInfo();
			uLogInfo.UserId = uData.UserId;
			uLogInfo.AccountType = isFacebook == true ? ACCOUNT_LOG_TYPE.FACEBOOK_ACCOUNT : ACCOUNT_LOG_TYPE.NATIVE_ACCOUNT;
			uLogInfo.Username = isFacebook == true ? userfb.asMap().get("email").toString() : edtUsername.getText().toString();
			uLogInfo.Password = isFacebook == true ? "" : edtPassword.getText().toString();
			uLogInfo.FacebookID = isFacebook == true ? userfb.getId() : "";
			uLogInfo.AvatarData = uData.AvatarData == null ? new byte[0] : uData.AvatarData;
			uLogInfo.AvatarId = uData.AvatarId;
			uLogInfo.TotalUserFee = uData.TotalUserFee;

			ALTAppMgr.getInstance().setUserLogInfo(uLogInfo);

			onEventReceiver(SCREEN_UI.MAIN);
			// <<<<<<< .mine
			//
			// // // Load Ads list
			// // Bundle b = new Bundle();
			// // b.putString("userid",
			// // ALTAppMgr.getInstance().getUserLogInfo().UserId);
			// // b.putString("loadeditemcount", "0");
			// //
			// ALTAppMgr.getInstance().startServiceCmd(CMCmdHandler.COMMAND_GET_ADS_LIST_BY_USERID,
			// // new CMCmdHandler(), b, true);
			// =======
			// >>>>>>> .r34
		}
			break;

		case CMCmdHandler.COMMAND_CHECK_PUT_METHOD: {
			UserData uData = (UserData) bResult.getSerializable(ALTPTCMgr.REST_OBJECT_RETURN);
			Toast.makeText(this, uData.UserId + " : " + uData.Username, Toast.LENGTH_SHORT).show();
		}
			break;

		// case CMCmdHandler.COMMAND_GET_ADS_LIST_BY_USERID: {
		// AdsInfo[] adsLst = (AdsInfo[])
		// bResult.getSerializable(ALTPTCMgr.REST_OBJECT_RETURN);
		// ALTAppMgr.getInstance().setAdsLstData(Arrays.asList(adsLst));
		//
		// onEventReceiver(SCREEN_UI.MAIN);
		// }
		// break;

		default:
			break;

		}
	}

}